package me.android.library.utils.android;

import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import java.io.File;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import mylab.utils.common.ShellUtil;
import mylab.utils.common.StringUtil;

@Slf4j
@UtilityClass
public class InstallUtil {

    /**
     * App installation location settings values
     */
    public final int APP_INSTALL_AUTO = 0;
    public final int APP_INSTALL_INTERNAL = 1;
    public final int APP_INSTALL_EXTERNAL = 2;
    /**
     * Installation return code<br/>
     * install success.
     */
    public final int INSTALL_SUCCEEDED = 1;
    /**
     * Installation return code<br/>
     * the package is already installed.
     */
    public final int INSTALL_FAILED_ALREADY_EXISTS = -1;
    /**
     * Installation return code<br/>
     * the package archive file is invalid.
     */
    public final int INSTALL_FAILED_INVALID_APK = -2;
    /**
     * Installation return code<br/>
     * the URI passed in is invalid.
     */
    public final int INSTALL_FAILED_INVALID_URI = -3;
    /**
     * Installation return code<br/>
     * the package manager service found that the device didn't have enough
     * storage space to install the app.
     */
    public final int INSTALL_FAILED_INSUFFICIENT_STORAGE = -4;
    /**
     * Installation return code<br/>
     * a package is already installed with the same name.
     */
    public final int INSTALL_FAILED_DUPLICATE_PACKAGE = -5;
    /**
     * Installation return code<br/>
     * the requested shared user does not exist.
     */
    public final int INSTALL_FAILED_NO_SHARED_USER = -6;
    /**
     * Installation return code<br/>
     * a previously installed package of the same name has a different signature
     * than the new package (and the old package's data was not removed).
     */
    public final int INSTALL_FAILED_UPDATE_INCOMPATIBLE = -7;
    /**
     * Installation return code<br/>
     * the new package is requested a shared user which is already installed on
     * the device and does not have matching signature.
     */
    public final int INSTALL_FAILED_SHARED_USER_INCOMPATIBLE = -8;
    /**
     * Installation return code<br/>
     * the new package uses a shared library that is not available.
     */
    public final int INSTALL_FAILED_MISSING_SHARED_LIBRARY = -9;
    /**
     * Installation return code<br/>
     * the new package uses a shared library that is not available.
     */
    public final int INSTALL_FAILED_REPLACE_COULDNT_DELETE = -10;
    /**
     * Installation return code<br/>
     * the new package failed while optimizing and validating its dex files,
     * either because there was not enough storage or the validation failed.
     */
    public final int INSTALL_FAILED_DEXOPT = -11;
    /**
     * Installation return code<br/>
     * the new package failed because the current SDK version is older than that
     * required by the package.
     */
    public final int INSTALL_FAILED_OLDER_SDK = -12;
    /**
     * Installation return code<br/>
     * the new package failed because it contains a content provider with the
     * same authority as a provider already installed in the system.
     */
    public final int INSTALL_FAILED_CONFLICTING_PROVIDER = -13;
    /**
     * Installation return code<br/>
     * the new package failed because the current SDK version is newer than that
     * required by the package.
     */
    public final int INSTALL_FAILED_NEWER_SDK = -14;
    /**
     * Installation return code<br/>
     * the new package failed because it has specified that it is a test-only
     * flag.
     */
    public final int INSTALL_FAILED_TEST_ONLY = -15;
    /**
     * Installation return code<br/>
     * the package being installed contains native code, but none that is
     * compatible with the the device's CPU_ABI.
     */
    public final int INSTALL_FAILED_CPU_ABI_INCOMPATIBLE = -16;
    /**
     * Installation return code<br/>
     * the new package uses a feature that is not available.
     */
    public final int INSTALL_FAILED_MISSING_FEATURE = -17;
    /**
     * Installation return code<br/>
     * a secure container mount point couldn't be accessed on external media.
     */
    public final int INSTALL_FAILED_CONTAINER_ERROR = -18;
    /**
     * Installation return code<br/>
     * the new package couldn't be installed in the specified install location.
     */
    public final int INSTALL_FAILED_INVALID_INSTALL_LOCATION = -19;
    /**
     * Installation return code<br/>
     * the new package couldn't be installed in the specified install location
     * because the media is not available.
     */
    public final int INSTALL_FAILED_MEDIA_UNAVAILABLE = -20;
    /**
     * Installation return code<br/>
     * the new package couldn't be installed because the verification timed out.
     */
    public final int INSTALL_FAILED_VERIFICATION_TIMEOUT = -21;
    /**
     * Installation return code<br/>
     * the new package couldn't be installed because the verification did not
     * succeed.
     */
    public final int INSTALL_FAILED_VERIFICATION_FAILURE = -22;
    /**
     * Installation return code<br/>
     * the package changed from what the calling program expected.
     */
    public final int INSTALL_FAILED_PACKAGE_CHANGED = -23;
    /**
     * Installation return code<br/>
     * the new package is assigned a different UID than it previously held.
     */
    public final int INSTALL_FAILED_UID_CHANGED = -24;
    /**
     * Installation return code<br/>
     * if the parser was given a path that is not a file, or does not end with
     * the expected '.apk' extension.
     */
    public final int INSTALL_PARSE_FAILED_NOT_APK = -100;
    /**
     * Installation return code<br/>
     * if the parser was unable to retrieve the AndroidManifest.xml file.
     */
    public final int INSTALL_PARSE_FAILED_BAD_MANIFEST = -101;
    /**
     * Installation return code<br/>
     * if the parser encountered an unexpected exception.
     */
    public final int INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION = -102;
    /**
     * Installation return code<br/>
     * if the parser did not find any certificates in the .apk.
     */
    public final int INSTALL_PARSE_FAILED_NO_CERTIFICATES = -103;
    /**
     * Installation return code<br/>
     * if the parser found inconsistent certificates on the files in the .apk.
     */
    public final int INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES = -104;
    /**
     * Installation return code<br/>
     * if the parser encountered a CertificateEncodingException in one of the
     * files in the .apk.
     */
    public final int INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING = -105;
    /**
     * Installation return code<br/>
     * if the parser encountered a bad or missing package name in the manifest.
     */
    public final int INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME = -106;
    /**
     * Installation return code<br/>
     * if the parser encountered a bad shared user id name in the manifest.
     */
    public final int INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID = -107;
    /**
     * Installation return code<br/>
     * if the parser encountered some structural problem in the manifest.
     */
    public final int INSTALL_PARSE_FAILED_MANIFEST_MALFORMED = -108;
    /**
     * Installation return code<br/>
     * if the parser did not find any actionable tags (instrumentation or
     * application) in the manifest.
     */
    public final int INSTALL_PARSE_FAILED_MANIFEST_EMPTY = -109;
    /**
     * Installation return code<br/>
     * if the system failed to install the package because of system issues.
     */
    public final int INSTALL_FAILED_INTERNAL_ERROR = -110;
    /**
     * Installation return code<br/>
     * other reason
     */
    public final int INSTALL_FAILED_OTHER = -1000000;
    /**
     * Uninstall return code<br/>
     * uninstall success.
     */
    public final int DELETE_SUCCEEDED = 1;
    /**
     * Uninstall return code<br/>
     * uninstall fail if the system failed to delete the package for an
     * unspecified reason.
     */
    public final int DELETE_FAILED_INTERNAL_ERROR = -1;
    /**
     * Uninstall return code<br/>
     * uninstall fail if the system failed to delete the package because it is
     * the active DevicePolicy manager.
     */
    public final int DELETE_FAILED_DEVICE_POLICY_MANAGER = -2;
    /**
     * Uninstall return code<br/>
     * uninstall fail if pcakge name is invalid
     */
    public final int DELETE_FAILED_INVALID_PACKAGE = -3;
    /**
     * Uninstall return code<br/>
     * uninstall fail if permission denied
     */
    public final int DELETE_FAILED_PERMISSION_DENIED = -4;
    public final int REQUEST_CODE_UNKNOWN_APP = 1000;


    public String getApplicationId(Context cx) {
        PackageManager pm = cx.getPackageManager();
        try {
            return pm.getApplicationInfo(cx.getPackageName(), 0).processName;
        } catch (NameNotFoundException e) {
            return null;
        }
    }

    public int getVersionCode(Context cx) {
        PackageManager pm = cx.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(cx.getPackageName(), 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            return 0;
        }
    }

    public String getVersionName(Context cx) {
        PackageManager pm = cx.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(cx.getPackageName(), 0);
            return pi.versionName;
        } catch (NameNotFoundException e) {
            return null;
        }
    }

    public void installApk(Context cx, Uri uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        cx.startActivity(intent);
    }

    public void installApk(Activity activity, File file, String authority) {
        Uri uri = Uri.fromFile(file);
        // 判断版本大于等于7.0
        uri = FileProvider.getUriForFile(activity, authority, file);

        // 判断版本大于等于8.0
        boolean hasInstallPermission = activity.getPackageManager().canRequestPackageInstalls();
        if (hasInstallPermission) {
            //安装应用
            installApk(activity, uri);
        } else {
            //跳转至“安装未知应用”权限界面，引导用户开启权限
            uri = Uri.parse("package:" + activity.getPackageName());
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, uri);
            ClipData clipData = ClipData.newRawUri("uri", uri);
            intent.setClipData(clipData);

            activity.startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP);
        }
    }

    public void installApk(Activity activity, Uri uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // 给目标应用一个临时授权
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }


    /**
     * install according conditions
     * <ul>
     * <li>if system application or rooted, see
     * {@link #installSilent(Context, String)}</li>
     * <li>else see {@link #installNormal(Context, String)}</li>
     * </ul>
     */
    public int install(Context context, String filePath) {
        if (InstallUtil.isSystemApplication(context) || ShellUtil.checkRootPermission()) {
            return installSilent(context, filePath);
        }
        return installNormal(context, filePath) ? INSTALL_SUCCEEDED : INSTALL_FAILED_INVALID_URI;
    }

    /**
     * install package normal by system intent
     */
    public boolean installNormal(Context context, String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()
                || file.length() <= 0) {
            return false;
        }

        i.setDataAndType(Uri.parse("file://" + filePath),
                "application/vnd.android.package-archive");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        return true;
    }

    /**
     * install package silent by root
     * <ul>
     * <strong>Attentions:</strong>
     * <li>Don't call this on the ui thread, it may costs some times.</li>
     * <li>You should add <strong>android.permission.INSTALL_PACKAGES</strong>
     * in manifest, so no need to request root permission, if you are system
     * app.</li>
     * <li>Default pm install params is "-r".</li>
     * </ul>
     */
    public int installSilent(Context context, String filePath) {
        return installSilent(context, filePath, " -r "
                + getInstallLocationParams());
    }

    /**
     * install package silent by root
     * <ul>
     * <strong>Attentions:</strong>
     * <li>Don't call this on the ui thread, it may costs some times.</li>
     * <li>You should add <strong>android.permission.INSTALL_PACKAGES</strong>
     * in manifest, so no need to request root permission, if you are system
     * app.</li>
     * </ul>
     */
    public int installSilent(Context context, String filePath, String pmParams) {
        if (filePath == null || filePath.isEmpty()) {
            return INSTALL_FAILED_INVALID_URI;
        }

        File file = new File(filePath);
        if (file.length() <= 0 || !file.exists() || !file.isFile()) {
            return INSTALL_FAILED_INVALID_URI;
        }

        /*
         * if context is system app, don't need root permission, but should add
         * <uses-permission android:name="android.permission.INSTALL_PACKAGES"/> in mainfest
         */
        String command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install " +
                (pmParams == null ? "" : pmParams) + " " +
                filePath.replace(" ", "\\ ");
        ShellUtil.CommandResult commandResult = ShellUtil.execCommand(
                command,
                !isSystemApplication(context),
                true);

        String successMsg = commandResult.getSuccessMsg();
        String errorMsg = commandResult.getErrorMsg();

        if (commandResult.getSuccessMsg() != null
                && (successMsg.contains("Success") || successMsg
                .contains("success"))) {
            return INSTALL_SUCCEEDED;
        }

        log.info("installSilent successMsg:{} , ErrorMsg:{}", successMsg, errorMsg);
        if (errorMsg == null) {
            return INSTALL_FAILED_OTHER;
        }
        if (errorMsg.contains("INSTALL_FAILED_ALREADY_EXISTS")) {
            return INSTALL_FAILED_ALREADY_EXISTS;
        }
        if (errorMsg.contains("INSTALL_FAILED_INVALID_APK")) {
            return INSTALL_FAILED_INVALID_APK;
        }
        if (errorMsg.contains("INSTALL_FAILED_INVALID_URI")) {
            return INSTALL_FAILED_INVALID_URI;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_INSUFFICIENT_STORAGE")) {
            return INSTALL_FAILED_INSUFFICIENT_STORAGE;
        }
        if (errorMsg.contains("INSTALL_FAILED_DUPLICATE_PACKAGE")) {
            return INSTALL_FAILED_DUPLICATE_PACKAGE;
        }
        if (errorMsg.contains("INSTALL_FAILED_NO_SHARED_USER")) {
            return INSTALL_FAILED_NO_SHARED_USER;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_UPDATE_INCOMPATIBLE")) {
            return INSTALL_FAILED_UPDATE_INCOMPATIBLE;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_SHARED_USER_INCOMPATIBLE")) {
            return INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_MISSING_SHARED_LIBRARY")) {
            return INSTALL_FAILED_MISSING_SHARED_LIBRARY;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_REPLACE_COULDNT_DELETE")) {
            return INSTALL_FAILED_REPLACE_COULDNT_DELETE;
        }
        if (errorMsg.contains("INSTALL_FAILED_DEXOPT")) {
            return INSTALL_FAILED_DEXOPT;
        }
        if (errorMsg.contains("INSTALL_FAILED_OLDER_SDK")) {
            return INSTALL_FAILED_OLDER_SDK;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_CONFLICTING_PROVIDER")) {
            return INSTALL_FAILED_CONFLICTING_PROVIDER;
        }
        if (errorMsg.contains("INSTALL_FAILED_NEWER_SDK")) {
            return INSTALL_FAILED_NEWER_SDK;
        }
        if (errorMsg.contains("INSTALL_FAILED_TEST_ONLY")) {
            return INSTALL_FAILED_TEST_ONLY;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_CPU_ABI_INCOMPATIBLE")) {
            return INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
        }
        if (errorMsg.contains("INSTALL_FAILED_MISSING_FEATURE")) {
            return INSTALL_FAILED_MISSING_FEATURE;
        }
        if (errorMsg.contains("INSTALL_FAILED_CONTAINER_ERROR")) {
            return INSTALL_FAILED_CONTAINER_ERROR;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_INVALID_INSTALL_LOCATION")) {
            return INSTALL_FAILED_INVALID_INSTALL_LOCATION;
        }
        if (errorMsg.contains("INSTALL_FAILED_MEDIA_UNAVAILABLE")) {
            return INSTALL_FAILED_MEDIA_UNAVAILABLE;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_VERIFICATION_TIMEOUT")) {
            return INSTALL_FAILED_VERIFICATION_TIMEOUT;
        }
        if (errorMsg
                .contains("INSTALL_FAILED_VERIFICATION_FAILURE")) {
            return INSTALL_FAILED_VERIFICATION_FAILURE;
        }
        if (errorMsg.contains("INSTALL_FAILED_PACKAGE_CHANGED")) {
            return INSTALL_FAILED_PACKAGE_CHANGED;
        }
        if (errorMsg.contains("INSTALL_FAILED_UID_CHANGED")) {
            return INSTALL_FAILED_UID_CHANGED;
        }
        if (errorMsg.contains("INSTALL_PARSE_FAILED_NOT_APK")) {
            return INSTALL_PARSE_FAILED_NOT_APK;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_BAD_MANIFEST")) {
            return INSTALL_PARSE_FAILED_BAD_MANIFEST;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION")) {
            return INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_NO_CERTIFICATES")) {
            return INSTALL_PARSE_FAILED_NO_CERTIFICATES;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES")) {
            return INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING")) {
            return INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME")) {
            return INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID")) {
            return INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_MANIFEST_MALFORMED")) {
            return INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
        }
        if (errorMsg
                .contains("INSTALL_PARSE_FAILED_MANIFEST_EMPTY")) {
            return INSTALL_PARSE_FAILED_MANIFEST_EMPTY;
        }
        if (errorMsg.contains("INSTALL_FAILED_INTERNAL_ERROR")) {
            return INSTALL_FAILED_INTERNAL_ERROR;
        }
        return INSTALL_FAILED_OTHER;
    }

    /**
     * uninstall according conditions
     * <ul>
     * <li>if system application or rooted, see
     * {@link #uninstallSilent(Context, String)}</li>
     * <li>else see {@link #uninstallNormal(Context, String)}</li>
     * </ul>
     */
    public int uninstall(Context context, String packageName) {
        if (InstallUtil.isSystemApplication(context)
                || ShellUtil.checkRootPermission()) {
            return uninstallSilent(context, packageName);
        }
        return uninstallNormal(context, packageName) ? DELETE_SUCCEEDED
                : DELETE_FAILED_INVALID_PACKAGE;
    }

    /**
     * uninstall package normal by system intent
     */
    public boolean uninstallNormal(Context context, String packageName) {
        if (StringUtil.isEmpty(packageName)) {
            return false;
        }

        Intent i = new Intent(Intent.ACTION_DELETE,
                Uri.parse("package:" + packageName));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        return true;
    }

    /**
     * uninstall package and clear data of app silent by root
     */
    public int uninstallSilent(Context context, String packageName) {
        return uninstallSilent(context, packageName, true);
    }

    /**
     * uninstall package silent by root
     * <ul>
     * <strong>Attentions:</strong>
     * <li>Don't call this on the ui thread, it may costs some times.</li>
     * <li>You should add <strong>android.permission.DELETE_PACKAGES</strong> in
     * manifest, so no need to request root permission, if you are system app.</li>
     * </ul>
     *
     * @param context     file path of package
     * @param packageName package name of app
     * @param isKeepData  whether keep the data and cache directories around after
     *                    package removal
     * @return <ul>
     * <li>{@link #DELETE_SUCCEEDED} means uninstall success</li>
     * <li>{@link #DELETE_FAILED_INTERNAL_ERROR} means internal error</li>
     * <li>{@link #DELETE_FAILED_INVALID_PACKAGE} means package name
     * error</li>
     * <li>{@link #DELETE_FAILED_PERMISSION_DENIED} means permission
     * denied</li>
     */
    public int uninstallSilent(Context context, String packageName, boolean isKeepData) {
        if (StringUtil.isEmpty(packageName)) {
            return DELETE_FAILED_INVALID_PACKAGE;
        }

        /*
         * if context is system app, don't need root permission, but should add
         * <uses-permission android:name="android.permission.DELETE_PACKAGES" />
         * in mainfest
         */
        String command = "LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall" +
                (isKeepData ? " -k " : " ") +
                packageName.replace(" ", "\\ ");
        ShellUtil.CommandResult commandResult = ShellUtil.execCommand(
                command,
                !isSystemApplication(context), true);
        String successMsg = commandResult.getSuccessMsg();
        String errorMsg = commandResult.getErrorMsg();

        if (successMsg != null
                && (successMsg.contains("Success") || successMsg
                .contains("success"))) {
            return DELETE_SUCCEEDED;
        }
        log.info("uninstallSilent successMsg:{}, ErrorMsg:{}", successMsg, errorMsg);
        if (errorMsg == null) {
            return DELETE_FAILED_INTERNAL_ERROR;
        }
        if (errorMsg.contains("Permission denied")) {
            return DELETE_FAILED_PERMISSION_DENIED;
        }
        return DELETE_FAILED_INTERNAL_ERROR;
    }

    /**
     * whether context is system application
     */
    public boolean isSystemApplication(Context context) {
        if (context == null) {
            return false;
        }

        return isSystemApplication(context, context.getPackageName());
    }

    /**
     * whether packageName is system application
     */
    public boolean isSystemApplication(Context context, String packageName) {
        if (context == null) {
            return false;
        }

        return isSystemApplication(context.getPackageManager(), packageName);
    }

    /**
     * whether packageName is system application
     *
     * @return <ul>
     * <li>if packageManager is null, return false</li>
     * <li>if package name is null or is empty, return false</li>
     * <li>if package name not exit, return false</li>
     * <li>if package name exit, but not system app, return false</li>
     * <li>else return true</li>
     * </ul>
     */
    public boolean isSystemApplication(PackageManager packageManager, String packageName) {
        if (packageManager == null || StringUtil.isEmpty(packageName)) {
            return false;
        }

        try {
            ApplicationInfo app = packageManager.getApplicationInfo(
                    packageName, 0);
            return (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0;
        } catch (NameNotFoundException ignored) {
        }
        return false;
    }

    /**
     * get system install location<br/>
     * can be set by System Menu Setting->Storage->Prefered install location
     */
    public int getInstallLocation() {
        ShellUtil.CommandResult commandResult = ShellUtil
                .execCommand("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm get-install-location",
                        false, true);
        if (commandResult.getResult() == 0 && StringUtil.isNotEmpty(commandResult.getSuccessMsg())) {
            try {
                int location = Integer.parseInt(commandResult.getSuccessMsg().substring(0, 1));
                switch (location) {
                    case APP_INSTALL_INTERNAL:
                        return APP_INSTALL_INTERNAL;
                    case APP_INSTALL_EXTERNAL:
                        return APP_INSTALL_EXTERNAL;
                }
            } catch (NumberFormatException e) {
                log.info("pm get-install-location error");
            }
        }
        return APP_INSTALL_AUTO;
    }

    /**
     * get params for pm install location
     */
    private String getInstallLocationParams() {
        int location = getInstallLocation();
        return switch (location) {
            case APP_INSTALL_INTERNAL -> "-f";
            case APP_INSTALL_EXTERNAL -> "-s";
            default -> "";
        };
    }

    /**
     * start InstalledAppDetails Activity
     */
    public void startInstalledAppDetails(Context context, String packageName) {
        Intent intent = new Intent();
        int sdkVersion = Build.VERSION.SDK_INT;
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", packageName, null));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
